package model

import (
	"go-vue/admin/conf"
)

// SystemMenuApiList 系统菜单 接口权限
type SystemMenuApiList struct {
	Id     int64  `xorm:"autoincr id"`
	MenuId int64  `json:"menu_id" xorm:"menu_id"`
	Code   string `json:"code" xorm:"code"`
	Remark string `json:"remark" xorm:"remark"`
}

func (menu *SystemMenuApiList) One() *SystemMenuApiList {
	exist, err := conf.DbEngine.Get(menu)
	if err != nil || exist == false {
		return nil
	}
	return menu
}

// GetListByMenuId 根据菜单id获取菜单权限列表
func (menu *SystemMenuApiList) GetListByMenuId(menuId int64) (list []SystemMenuApiList) {
	err := conf.DbEngine.Where("menu_id = ?", menuId).Find(&list)
	if err != nil {
		return nil
	}
	return
}

// GetAllMenuApiList 获取系统所有菜单权限api
func (menu *SystemMenuApiList) GetAllMenuApiList() map[int64][]SystemMenuApiList {
	var list []SystemMenuApiList
	res := make(map[int64][]SystemMenuApiList)
	conf.DbEngine.Find(&list)

	for _, item := range list {
		if _, ok := res[item.MenuId]; ok == false {
			res[item.MenuId] = make([]SystemMenuApiList, 0)
		}
		res[item.MenuId] = append(res[item.MenuId], item)
	}
	return res
}

// GetAllMenuIds 获取系统所有菜单权限api
func (menu *SystemMenuApiList) GetAllMenuIds(permissions []string) []int64 {
	var list []SystemMenuApiList
	err := conf.DbEngine.In("code", permissions).Distinct("menu_id").Find(&list)
	if err != nil {
		return nil
	}
	var ids []int64
	for _, apiList := range list {
		ids = append(ids, apiList.MenuId)
	}

	return ids
}
